package com.vibeplayer.app.activity;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.pm.PackageManager;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.StringRes;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.vibeplayer.app.R;
import com.vibeplayer.app.adapter.FileAdapter;
import com.vibeplayer.app.model.FileModel;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class FileExplorerActivity extends AppCompatActivity implements FileAdapter.FileClickListener {
    
    private static final int PERMISSION_REQUEST_CODE = 1001;
    
    private RecyclerView recyclerViewFiles;
    private TextView txtCurrentPath;
    private TextView txtEmptyDir;
    private TextView txtSelectedCount;
    private Button btnImport;
    private ProgressBar progressBar;
    private Toolbar toolbar;
    
    private FileAdapter adapter;
    private List<FileModel> files = new ArrayList<>();
    private File currentDirectory;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file_explorer);
        
        // 初始化视图
        initViews();
        
        // 检查权限
        checkPermissions();
    }
    
    private void initViews() {
        toolbar = findViewById(R.id.toolbar);
        
        // 直接设置Toolbar的标题和导航图标，而不使用setSupportActionBar
        toolbar.setTitle(R.string.import_music);
        toolbar.setNavigationIcon(R.drawable.ic_arrow_back);
        toolbar.setNavigationOnClickListener(v -> onBackPressed());
        
        recyclerViewFiles = findViewById(R.id.recyclerViewFiles);
        txtCurrentPath = findViewById(R.id.txtCurrentPath);
        txtEmptyDir = findViewById(R.id.txtEmptyDir);
        txtSelectedCount = findViewById(R.id.txtSelectedCount);
        btnImport = findViewById(R.id.btnImport);
        progressBar = findViewById(R.id.progressBar);
        
        recyclerViewFiles.setLayoutManager(new LinearLayoutManager(this));
        adapter = new FileAdapter(this, files, this);
        recyclerViewFiles.setAdapter(adapter);
        
        btnImport.setOnClickListener(v -> importSelectedFiles());
    }
    
    private void checkPermissions() {
        boolean hasPermission = false;
        
        // 适配Android 13及以上版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            hasPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_MEDIA_AUDIO)
                    == PackageManager.PERMISSION_GRANTED;
            
            if (!hasPermission) {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.READ_MEDIA_AUDIO},
                        PERMISSION_REQUEST_CODE);
                return;
            }
        } 
        // 适配Android 10及以下版本
        else {
            hasPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                    == PackageManager.PERMISSION_GRANTED;
            
            if (!hasPermission) {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                        PERMISSION_REQUEST_CODE);
                return;
            }
        }
        
        // 权限已授予，加载文件
        loadRootDirectory();
    }
    
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限已授予，加载文件
                loadRootDirectory();
            } else {
                // 显示权限未授予提示
                showEmptyView(R.string.storage_permission_required);
            }
        }
    }
    
    private void showEmptyView(@StringRes int messageResId) {
        progressBar.setVisibility(View.GONE);
        recyclerViewFiles.setVisibility(View.GONE);
        txtEmptyDir.setText(messageResId);
        txtEmptyDir.setVisibility(View.VISIBLE);
    }
    
    private void loadRootDirectory() {
        // 加载外部存储根目录
        File externalStorageDir = Environment.getExternalStorageDirectory();
        loadDirectory(externalStorageDir);
    }
    
    private void loadDirectory(File directory) {
        progressBar.setVisibility(View.VISIBLE);
        txtEmptyDir.setVisibility(View.GONE);
        recyclerViewFiles.setVisibility(View.GONE);
        
        currentDirectory = directory;
        txtCurrentPath.setText(directory.getAbsolutePath());
        
        // 在后台线程中加载文件列表
        new LoadFilesTask().execute(directory);
    }
    
    @Override
    public void onFileClick(int position) {
        FileModel fileModel = files.get(position);
        if (fileModel.isDirectory()) {
            // 如果是目录，进入该目录
            loadDirectory(fileModel.getFile());
        } else if (fileModel.isAudioFile()) {
            // 如果是音频文件，选择它
            adapter.enableSelectionMode();
            fileModel.setSelected(true);
            adapter.notifyItemChanged(position);
            onSelectionChanged(adapter.getSelectedFiles());
        }
    }
    
    @Override
    public void onSelectionChanged(List<FileModel> selectedFiles) {
        int count = selectedFiles.size();
        if (count > 0) {
            txtSelectedCount.setText(getString(R.string.files_selected, count));
            btnImport.setEnabled(true);
        } else {
            txtSelectedCount.setText(R.string.no_files_selected);
            btnImport.setEnabled(false);
        }
    }
    
    @Override
    public void onSelectionModeChanged(boolean selectionMode) {
        // 刷新选项菜单
        if (selectionMode) {
            toolbar.inflateMenu(R.menu.menu_file_selection);
            toolbar.setOnMenuItemClickListener(this::onMenuItemClick);
        } else {
            toolbar.getMenu().clear();
        }
    }
    
    private boolean onMenuItemClick(MenuItem item) {
        int itemId = item.getItemId();
        
        if (itemId == R.id.action_select_all) {
            adapter.selectAll();
            return true;
        } else if (itemId == R.id.action_deselect_all) {
            adapter.deselectAll();
            return true;
        }
        
        return false;
    }
    
    @Override
    public void onBackPressed() {
        if (adapter.isSelectionMode()) {
            // 如果处于选择模式，退出选择模式
            adapter.disableSelectionMode();
        } else if (currentDirectory != null && !currentDirectory.equals(Environment.getExternalStorageDirectory())) {
            // 如果不在根目录，返回上一级目录
            loadDirectory(currentDirectory.getParentFile());
        } else {
            // 否则，关闭Activity
            super.onBackPressed();
        }
    }
    
    private void importSelectedFiles() {
        List<FileModel> selectedFiles = adapter.getSelectedFiles();
        if (selectedFiles.isEmpty()) {
            return;
        }
        
        // 开始导入任务
        new ImportFilesTask().execute(selectedFiles.toArray(new FileModel[0]));
    }
    
    /**
     * 加载文件列表的异步任务
     */
    private class LoadFilesTask extends AsyncTask<File, Void, List<FileModel>> {
        
        @Override
        protected List<FileModel> doInBackground(File... files) {
            List<FileModel> fileList = new ArrayList<>();
            
            if (files.length == 0 || files[0] == null || !files[0].exists() || !files[0].isDirectory()) {
                return fileList;
            }
            
            File directory = files[0];
            File[] listFiles = directory.listFiles();
            
            if (listFiles == null) {
                return fileList;
            }
            
            // 排序：文件夹在前，文件在后，按字母顺序排序
            Arrays.sort(listFiles, new Comparator<File>() {
                @Override
                public int compare(File f1, File f2) {
                    if (f1.isDirectory() && !f2.isDirectory()) {
                        return -1;
                    } else if (!f1.isDirectory() && f2.isDirectory()) {
                        return 1;
                    } else {
                        return f1.getName().compareToIgnoreCase(f2.getName());
                    }
                }
            });
            
            for (File file : listFiles) {
                // 忽略隐藏文件
                if (!file.isHidden()) {
                    // 如果是目录或音频文件，添加到列表
                    if (file.isDirectory() || isAudioFile(file.getName())) {
                        fileList.add(new FileModel(file));
                    }
                }
            }
            
            return fileList;
        }
        
        @Override
        protected void onPostExecute(List<FileModel> result) {
            progressBar.setVisibility(View.GONE);
            
            files.clear();
            files.addAll(result);
            adapter.notifyDataSetChanged();
            
            if (files.isEmpty()) {
                // 检查是否有存储权限
                boolean hasStoragePermission = false;
                
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                    // Android 13+检查READ_MEDIA_AUDIO权限
                    hasStoragePermission = ContextCompat.checkSelfPermission(
                            FileExplorerActivity.this, 
                            Manifest.permission.READ_MEDIA_AUDIO) 
                            == PackageManager.PERMISSION_GRANTED;
                } else {
                    // 较低版本检查READ_EXTERNAL_STORAGE权限
                    hasStoragePermission = ContextCompat.checkSelfPermission(
                            FileExplorerActivity.this, 
                            Manifest.permission.READ_EXTERNAL_STORAGE) 
                            == PackageManager.PERMISSION_GRANTED;
                }
                
                if (!hasStoragePermission) {
                    // 如果没有权限，显示权限相关提示
                    showEmptyView(R.string.storage_permission_required);
                } else {
                    // 有权限但没有找到音频文件，根据当前目录显示不同的提示
                    if (currentDirectory.equals(Environment.getExternalStorageDirectory())) {
                        showEmptyView(R.string.no_audio_files_root);
                    } else {
                        showEmptyView(R.string.no_audio_files_current);
                    }
                }
            } else {
                txtEmptyDir.setVisibility(View.GONE);
                recyclerViewFiles.setVisibility(View.VISIBLE);
            }
        }
        
        private boolean isAudioFile(String fileName) {
            String lowerCaseName = fileName.toLowerCase();
            return lowerCaseName.endsWith(".mp3") || lowerCaseName.endsWith(".wav") ||
                   lowerCaseName.endsWith(".ogg") || lowerCaseName.endsWith(".flac") ||
                   lowerCaseName.endsWith(".aac") || lowerCaseName.endsWith(".wma") ||
                   lowerCaseName.endsWith(".m4a") || lowerCaseName.endsWith(".opus");
        }
    }
    
    /**
     * 导入文件的异步任务
     */
    private class ImportFilesTask extends AsyncTask<FileModel, Integer, Boolean> {
        
        private ProgressDialog progressDialog;
        private int totalFiles;
        private int importedFiles = 0;
        private List<String> importedFilePaths = new ArrayList<>();
        
        @Override
        protected void onPreExecute() {
            progressDialog = new ProgressDialog(FileExplorerActivity.this);
            progressDialog.setTitle(R.string.importing_files);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            progressDialog.setCancelable(false);
            progressDialog.show();
        }
        
        @Override
        protected Boolean doInBackground(FileModel... fileModels) {
            totalFiles = fileModels.length;
            progressDialog.setMax(totalFiles);
            
            for (FileModel fileModel : fileModels) {
                if (fileModel.isAudioFile()) {
                    try {
                        // 直接使用原始文件路径，不复制文件
                        importedFilePaths.add(fileModel.getPath());
                        importedFiles++;
                        publishProgress(importedFiles);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            
            return importedFiles > 0;
        }
        
        @Override
        protected void onProgressUpdate(Integer... values) {
            progressDialog.setProgress(values[0]);
        }
        
        @Override
        protected void onPostExecute(Boolean success) {
            progressDialog.dismiss();
            
            if (success) {
                Toast.makeText(FileExplorerActivity.this, R.string.import_success, Toast.LENGTH_SHORT).show();
                
                // 通知媒体扫描器扫描导入的文件
                MediaScannerConnection.scanFile(
                        FileExplorerActivity.this,
                        importedFilePaths.toArray(new String[0]),
                        null,
                        (path, uri) -> {
                            // 扫描完成
                        }
                );
                
                // 设置结果并关闭Activity
                setResult(RESULT_OK);
                finish();
            } else {
                Toast.makeText(FileExplorerActivity.this, R.string.import_failed, Toast.LENGTH_SHORT).show();
            }
        }
    }
} 